const utils = {
	commonUrl: function() {
		// let domain = '/api/';
		// let domain = 'http://10.35.5.42:8761/';//打包地址
		let domain = 'http://192.168.1.38:8761/'
		// let domain = 'https://jm.xzldit.com:8847/api/'
		return domain;
	},
	judgeObj: function() {
		// let loginPage = 'http://fwdt.gzjmzy.cn:6331/ui/oper/login/toLoginPage.jspx';
		let loginPage = 'https://crp.gzeic.com/xsgl/xs/login/login.aspx';
		let obj = {
			loginPage:loginPage,
		}
		return obj;
	},
	
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success || 'none',
			duration: duration || 3000
		})
	},
	
	modal: function(title, content, showCancel = false, callback, confirmColor, confirmText, cancelColor,
		cancelText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: cancelColor || "#555",
			confirmColor: confirmColor || "#e41f19",
			confirmText: confirmText || "确定",
			cancelText: cancelText || "取消",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() != "iphone"
	},
	isIosOrAndroid() {
		var u = navigator.userAgent
		var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
		if (isAndroid) {
			return 1
		}
		var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		if (isiOS) {
			return 2
		}
		return 0
	},
	isIphoneX: function() {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
		const model = res.model.replace(/\s/g, "").toLowerCase()
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	
	base64ToBlob(urlData, type) {
		let arr = urlData.split(',');
		let mime = arr[0].match(/:(.*?);/)[1] || type;
		// 去掉url的头，并转化为byte
		let bytes = window.atob(arr[1]);
		// 处理异常,将ascii码小于0的转换为大于0
		let ab = new ArrayBuffer(bytes.length);
		// 生成视图（直接针对内存）：8位无符号整数，长度1个字节
		let ia = new Uint8Array(ab);
		for (let i = 0; i < bytes.length; i++) {
		  ia[i] = bytes.charCodeAt(i);
		}
		let conversions = new Blob([ab], {
		  type: mime
		});
		window.URL = window.URL || window.webkitURL; //blob对象转换为blob-url
		let blobUrl = window.URL.createObjectURL(conversions);
		return blobUrl;
	},

	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param {*} postData 请求参数
	 * @param string method 请求方式
	 *  GET or POST
	 * @param string contentType 数据格式
	 *  'application/x-www-form-urlencoded'
	 *  'application/json'
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	requestGet: function(url, postData = {}, method = "GET", contentType = "application/json; charset=utf-8",
		isDelay,
		hideLoading) {
		//接口请求
		let loadding = false;
		utils.delayed && uni.hideLoading();
		clearTimeout(utils.delayed);
		utils.delayed = null;
		if (!hideLoading) {
			utils.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}

		return new Promise((resolve, reject) => {
			uni.request({
				url: utils.commonUrl() + url,
				data: postData,
				header: {
					'content-type': contentType,
					'Authorization': utils.getToken()
					// 'Authorization': ""
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if (res.statusCode === 200) {
						resolve(res.data);
					} else {
						reject(res.data.message);
					}
				},
				fail: (res) => {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete: function(res) {
					clearTimeout(utils.delayed)
					utils.delayed = null;
					if (res.statusCode === 200) {
						if (res.data.status === 200) {
							uni.hideLoading()
						} else {
							uni.hideLoading()
							utils.toast(res.data.message)
						}
					} else if (res.statusCode === 401) {
						utils.toast('登录已失效,请重新登录~')
						uni.removeStorageSync("token")
						uni.removeStorageSync("user")
						uni.removeStorageSync("name")
						uni.removeStorageSync("phone")
						//token过期处理
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							})
							// location.href = utils.judgeObj().loginPage
						}, 2000);
					} else {
						utils.toast('网络异常，请稍后重试~')
					}
				}
			})
		})
	},
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param {*} postData 请求参数
	 * @param string method 请求方式
	 *  GET or POST
	 * @param string contentType 数据格式
	 *  'application/x-www-form-urlencoded'
	 *  'application/json'
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, postData = {}, method = "POST", contentType = "application/json; charset=utf-8", isDelay,
		hideLoading) {
		//接口请求
		let loadding = false;
		utils.delayed && uni.hideLoading();
		clearTimeout(utils.delayed);
		utils.delayed = null;
		if (!hideLoading) {
			utils.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}

		return new Promise((resolve, reject) => {
			uni.request({
				url: utils.commonUrl() + url,
				data: postData,
				header: {
					'content-type': contentType,
					'Authorization': utils.getToken(),
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if (res.statusCode === 200) {
						resolve(res.data);
					} else {
						reject(res.data.message);
					}
				},
				fail: (res) => {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete: function(res) {
					clearTimeout(utils.delayed)
					utils.delayed = null;
					if (res.statusCode === 200) {
						if (res.data.status === 200) {
							uni.hideLoading();
							// utils.toast(res.data.message)
						} else {
							uni.hideLoading()
							utils.toast(res.data.message)
						}
					} else if (res.statusCode === 401) {
						utils.toast('登录已失效,请重新登录~')
						uni.removeStorageSync("token")
						uni.removeStorageSync("user")
						uni.removeStorageSync("name")
						uni.removeStorageSync("phone")
						//token过期处理
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							})
							// location.href = utils.judgeObj().loginPage
						}, 2000);
					} else {
						utils.toast('接口请求失败，请稍后重试~')
					}
				}
			})
		})
	},
	requestDownLoad: function(url, postData = {}, method = "POST", contentType = "application/json; charset=utf-8",
		isDelay,
		hideLoading) {
		//接口请求
		let loadding = false;
		utils.delayed && uni.hideLoading();
		clearTimeout(utils.delayed);
		utils.delayed = null;
		if (!hideLoading) {
			utils.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}

		return new Promise((resolve, reject) => {
			uni.request({
				url: utils.commonUrl() + url,
				data: postData,
				header: {
					'content-type': contentType,
					'Authorization': utils.getToken(),
				},
				responseType: 'arraybuffer',
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if (res.statusCode === 200) {
						resolve(res.data);
					} else {
						reject(res.data.message);
					}
				},
				fail: (res) => {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete: function(res) {}
			})
		})
	},
	/**
	 * 请求数据处理---扫码
	 * @param string url 请求地址
	 * @param {*} postData 请求参数
	 * @param string method 请求方式
	 *  GET or POST
	 * @param string contentType 数据格式
	 *  'application/x-www-form-urlencoded'
	 *  'application/json'
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	requestScan: function(url, postData = {}, method = "GET", contentType = "application/json; charset=utf-8",
		isDelay,
		hideLoading) {
		//接口请求
		let loadding = false;
		utils.delayed && uni.hideLoading();
		clearTimeout(utils.delayed);
		utils.delayed = null;
		if (!hideLoading) {
			utils.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}

		return new Promise((resolve, reject) => {
			uni.request({
				url: url,
				data: postData,
				header: {
					'content-type': contentType,
					'Authorization': utils.getToken()
					// 'Authorization': ""
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if (res.statusCode === 200) {
						resolve(res.data);
					} else {
						reject(res.data.message);
					}
				},
				fail: (res) => {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete: function(res) {
					clearTimeout(utils.delayed)
					utils.delayed = null;
					if (res.statusCode === 200) {
						if (res.data.status === 200) {
							uni.hideLoading()
						} else {
							uni.hideLoading()
							utils.toast(res.data.message)
						}
					} else if (res.statusCode === 401) {
						utils.toast('登录已失效,请重新登录~')
						uni.removeStorageSync("token")
						uni.removeStorageSync("user")
						uni.removeStorageSync("name")
						uni.removeStorageSync("phone")
						//token过期处理
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							})
							// location.href = utils.judgeObj().loginPage
						}, 2000);
					} else {
						utils.toast('网络异常，请稍后重试~')
					}
				}
			})
		})
	},

	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param [] postData 请求参数
	 * @param string method 请求方式
	 *  GET or POST
	 * @param string contentType 数据格式
	 *  'application/x-www-form-urlencoded'
	 *  'application/json'
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	requestArry: function(url, postData = [], method = "POST", contentType = "application/json; charset=utf-8",
		isDelay,
		hideLoading) {
		//接口请求
		let loadding = false;
		utils.delayed && uni.hideLoading();
		clearTimeout(utils.delayed);
		utils.delayed = null;
		if (!hideLoading) {
			utils.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}

		return new Promise((resolve, reject) => {
			uni.request({
				url: utils.commonUrl() + url,
				data: postData,
				header: {
					'content-type': contentType,
					'Authorization': utils.getToken()
					// 'Authorization': ""
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if (res.statusCode === 200) {
						resolve(res.data);
					} else {
						reject(res.data.message);
					}
				},
				fail: (res) => {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete: function(res) {
					clearTimeout(utils.delayed)
					utils.delayed = null;
					if (res.statusCode === 200) {
						if (res.data.status === 200) {
							uni.hideLoading()
						} else {
							uni.hideLoading()
							utils.toast(res.data.message)
						}
					} else if (res.statusCode === 401) {
						utils.toast('登录已失效,请重新登录~')
						uni.removeStorageSync("token")
						uni.removeStorageSync("user")
						uni.removeStorageSync("name")
						uni.removeStorageSync("phone")
						//token过期处理
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							})
							// location.href = utils.judgeObj().loginPage
						}, 2000);
					} else {
						utils.toast('网络异常，请稍后重试~')
					}
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string imgSrc 上传的文件
	 */
	uploadFile: function(url, imgSrc, moduleName) {
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: utils.commonUrl() + url+ '?moduleName=' + moduleName ,
				filePath: imgSrc, //blob格式，或者转base64，结果一样
				name: 'file',
				header: {
					'enctype': 'multipart/form-data',
					'Authorization': utils.getToken()
				},
				success: function(res) {
					uni.hideLoading()
					let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					if (data.status == 200) {
						//返回图片地址
						resolve(data)
					} else {
						utils.toast(res.message);
					}
				},
				fail: function(res) {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete:function(e) {
					reject(e)
				}
			})
		})
	},
	
	/**
	 * 上传文件-多个文件
	 * @param string url 请求地址
	 * @param string imgSrc 上传的文件list
	 */
	uploadFileMulti: function(url, imgSrc) {
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: utils.commonUrl() + url + '?moduleName=onlineimgs',
				files: imgSrc,
				header: {
					'enctype': 'multipart/form-data',
					'Authorization': utils.getToken()
				},
				success: function(res) {
					uni.hideLoading()
					let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					if (data.status == 200) {
						//返回图片地址
						resolve(data)
					} else {
						utils.toast(res.message);
					}
				},
				fail: function(res) {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},

	/**
	 * 上传文件-扫码专用
	 * @param string url 请求地址
	 * @param string imgSrc 上传的文件
	 */
	uploadFileQrcod: function(url, imgSrc) {
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: utils.commonUrl() + url,
				filePath: imgSrc, //blob格式，或者转base64，结果一样
				name: 'file',
				header: {
					'enctype': 'multipart/form-data',
					'Authorization': utils.getToken()
				},
				success: function(res) {
					uni.hideLoading()
					let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					if (data.status == 200) {
						//返回图片地址
						resolve(data)
					} else {
						utils.toast("解析二维码失败！")
					}
				},
				fail: function(res) {
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile, token) {
		uni.setStorageSync("token", token)
		uni.setStorageSync("mobile", mobile)
	},
	//获取token
	getToken: function() {
		return uni.getStorageSync("token")
	},
	//去空格
	trim: function(value) {
		return value.replace(/(^\s*)|(\s*$)/g, "");
	},
	//内容替换
	replaceAll: function(text, repstr, newstr) {
		return text.replace(new RegExp(repstr, "gm"), newstr);
	},
	//格式化手机号码
	formatNumber: function(num) {
		return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
	},
	//金额格式化
	rmoney: function(money) {
		return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,')
			.replace(
				/\,$/, '').split('').reverse().join('');
	},

	//日期格式化
	formatDate: function(formatStr, fdate) {
		if (fdate) {
			fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
			var fTime, fStr = 'ymdhis';
			if (!formatStr)
				formatStr = "y-m-d h:i:s";
			fTime = new Date(fdate);
			var month = fTime.getMonth() + 1;
			var day = fTime.getDate();
			var hours = fTime.getHours();
			var minu = fTime.getMinutes();
			var second = fTime.getSeconds();
			month = month < 10 ? '0' + month : month;
			day = day < 10 ? '0' + day : day;
			hours = hours < 10 ? ('0' + hours) : hours;
			minu = minu < 10 ? '0' + minu : minu;
			second = second < 10 ? '0' + second : second;
			var formatArr = [
				fTime.getFullYear().toString(),
				month.toString(),
				day.toString(),
				hours.toString(),
				minu.toString(),
				second.toString()
			]
			for (var i = 0; i < formatArr.length; i++) {
				formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
			}
			return formatStr;
		} else {
			return "";
		}
	},
	getDistance: function(lat1, lng1, lat2, lng2) {
		function Rad(d) {
			return d * Math.PI / 180.0;
		}
		if (!lat1 || !lng1) {
			return '';
		}
		// lat1用户的纬度
		// lng1用户的经度
		// lat2商家的纬度
		// lng2商家的经度
		let radLat1 = Rad(lat1);
		let radLat2 = Rad(lat2);
		let a = radLat1 - radLat2;
		let b = Rad(lng1) - Rad(lng2);
		let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) *
			Math.pow(
				Math.sin(b / 2), 2)));
		s = s * 6378.137;
		s = Math.round(s * 10000) / 10000;
		s = '(距您' + s.toFixed(2) + '公里)' //保留两位小数
		return s
	},
	isMobile: function(mobile) {
		if (!mobile) {
			utils.toast('请输入手机号码');
			return false
		}
		if (!mobile.match(/^1[3-9][0-9]\d{8}$/)) {
			utils.toast('手机号不正确');
			return false
		}
		return true
	},
	rgbToHex: function(r, g, b) {
		return "#" + utils.toHex(r) + utils.toHex(g) + utils.toHex(b)
	},
	toHex: function(n) {
		n = parseInt(n, 10);
		if (isNaN(n)) return "00";
		n = Math.max(0, Math.min(n, 255));
		return "0123456789ABCDEF".charAt((n - n % 16) / 16) +
			"0123456789ABCDEF".charAt(n % 16);
	},
	hexToRgb(hex) {
		let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		return result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : null;
	},
	transDate: function(date, fmt) {
		if (!date) {
			return '--'
		}
		let _this = new Date(date * 1000)
		let o = {
			'M+': _this.getMonth() + 1,
			'd+': _this.getDate(),
			'h+': _this.getHours(),
			'm+': _this.getMinutes(),
			's+': _this.getSeconds(),
			'q+': Math.floor((_this.getMonth() + 3) / 3),
			'S': _this.getMilliseconds()
		}
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		for (let k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[
					k]).length)))
			}
		}
		return fmt
	},
	isNumber: function(val) {
		let regPos = /^\d+(\.\d+)?$/; //非负浮点数
		let regNeg =
			/^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
		if (regPos.test(val) || regNeg.test(val)) {
			return true;
		} else {
			return false;
		}
	},
	//判断字符串是否为空
	isEmpty: function(str) {
		if (str === '' || str === undefined || str === null) {
			return true;
		} else {
			return false;
		}
	},
	expireTime: function(str) {
		if (!str) {
			return;
		}
		let NowTime = new Date().getTime();
		//IOS系统直接使用new Date('2018-10-29 11:25:21')，在IOS上获取不到对应的时间对象。
		let totalSecond = Date.parse(str.replace(/-/g, '/')) - NowTime || [];
		if (totalSecond < 0) {
			return;
		}
		return totalSecond / 1000
	},

	/**
	 * 统一下单请求
	 */
	payOrder: function(orderId) {
		let tradeType = 'JSAPI'
		// #ifdef APP-PLUS
		tradeType = 'APP'
		// #endif
		// #ifdef H5
		tradeType = 'MWEB'
		// #endif
		return new Promise(function(resolve, reject) {
			utils.request('pay/prepay', {
				orderId: orderId,
				tradeType: tradeType
			}, 'POST').then((res) => {
				if (res.errno === 0) {
					// #ifdef H5
					location.href = res.mwebOrderResult.mwebUrl + '&redirect_url=' +
						encodeURIComponent(utils.domain +
							'h5/#/pages/payResult/payResult?orderId=' + orderId)
					// #endif

					// #ifdef APP-PLUS
					let appOrderResult = res.appOrderResult;
					uni.requestPayment({
						provider: 'wxpay',
						orderInfo: {
							"appid": appOrderResult.appId,
							"noncestr": appOrderResult.nonceStr,
							"package": appOrderResult.packageValue,
							"partnerid": appOrderResult.partnerId,
							"prepayid": appOrderResult.prepayId,
							"timestamp": appOrderResult.timeStamp,
							"sign": appOrderResult.sign
						},
						success: function(res) {
							resolve(res);
						},
						fail: function(res) {
							reject(res);
						},
						complete: function(res) {
							reject(res);
						}
					});
					// #endif

					// #ifdef MP-WEIXIN
					let payParam = res.data;
					uni.requestPayment({
						'timeStamp': payParam.timeStamp,
						'nonceStr': payParam.nonceStr,
						'package': payParam.packageValue,
						'signType': payParam.signType,
						'paySign': payParam.paySign,
						'success': function(res) {
							resolve(res);
						},
						'fail': function(res) {
							reject(res);
						},
						'complete': function(res) {
							reject(res);
						}
					});
					// #endif
				} else {
					reject(res);
				}
			});
		});
	},
	
	// page请求参数
	PageEntity: function() {
		let  obj  = {
		  first: 1,
		  rows: 1000,
		  totalRecords: 1,
		  sortOrder: -1,
		  filters: {},
		  multiSortMeta: []
		}
		
		return obj;
	},
	
	// page请求参数处理
	filterSearchParam: function(pageInfo,name,value2,matchMode2,whereType2) {
		if(value2 != null) {
			pageInfo.filters[name.toString()] = {
				matchMode: matchMode2,
				value: value2,
				whereType: whereType2
			}
		} else {
			delete pageInfo.filters[name.toString()];
		}
		return pageInfo;
	},
	
	// 日期-时间格式化-返回年月日时分秒
	getTimer: function() {
		var date = new Date();
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		m = m < 10 ? '0' + m : m;
		var d = date.getDate();
		d = d < 10 ? '0' + d : d;
		var w = date.getDay();
		var w1 = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
		var h = date.getHours();
		h = h < 10 ? '0' + h : h;
		var min = date.getMinutes();
		min = min < 10 ? '0' + min : min;
		var s = date.getSeconds();
		s = s < 10 ? '0' + s : s;

		return   y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s ;
	},
	// 日期-时间格式化-返回年月日
	getDay: function() {
		var date = new Date();
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		m = m < 10 ? '0' + m : m;
		var d = date.getDate();
		d = d < 10 ? '0' + d : d;
		var w = date.getDay();
		var w1 = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
		var h = date.getHours();
		h = h < 10 ? '0' + h : h;
		var min = date.getMinutes();
		min = min < 10 ? '0' + min : min;
		var s = date.getSeconds();
		s = s < 10 ? '0' + s : s;
		
		return   y + '-' + m + '-' + d;
	},

	/**
	 * 调用微信登录
	 */
	login: function() {
		return new Promise(function(resolve, reject) {
			uni.login({
				success: function(res) {
					if (res.code) {
						resolve(res);
					} else {
						reject(res);
					}
				},
				fail: function(err) {
					reject(err);
				}
			});
		});
	},
	// 将一个对象中key对应的值赋值给另一个对象中的相同的key
	copyObjWhenKeyEqual(copyFrom, copyTo) {
	    const keysTo = Object.keys(copyTo);
	
	    for (const key of keysTo) {
	        if (copyFrom[key] !== undefined) {
	            copyTo[key] = copyFrom[key];
	        }
	    }
	    return copyTo;
	},
	// 富文本转化为纯文本
	formatrichtext(richtext) {
	    let content = richtext.replace(/<.+?>/g, '');    
	    content = content.replace(/ /ig, ''); /* 去除  */    
	    content = content.replace(/\s/ig, ''); /* 去除空格 */
	    return content;
	},
	// 判断对象所有元素是否有空元素
	isObjEmpty(obj) {
		let flag = true;
		var arr = Object.values(obj).filter(function (item) {
		    if (item != '' || item != null) {
		        return true			//过滤掉为空的项
		    }
		})
		
		let arr_v2 = [];
		for (let j of arr) {
		  if (j || j == 0) {
		    arr_v2.push(j)
		  }
		}
		console.log(arr)
		console.log(arr_v2)
		if (arr_v2.length == arr.length) {
			flag = false;
		}
		return flag
	},
	// js数组对象展平
	flatten(data) {
		return data.reduce((pre, { key, title, children = [] }) =>
			pre.concat([{ key, title }], this.flatten(children)), [])
	},
	// 数组太长时用二分查找，返回index
	binarySearch(arr, target,label){
	    let start = 0;
	    let end = arr.length - 1;
	    if(!end) return -1
	    if(end == 1){
	        return arr[0] === target ? 0 : -1 
	    }
	    let middle;
	    while(start <= end){
	        middle = (start + end) / 2 | 0; // 向下取整
	        if(arr[middle][label] === target){
	            return middle
	        }else if(target > arr[middle][label]){
	            start = middle + 1
	        }else{
	            end = middle - 1
	        }
	    }
	    return -1
	},
	randomNumber(len) {
		let num = '';
		for (let i = 0; i < len; i++) {
			num += Math.floor(Math.random() * 10);
		}
		return num;
	}
}

module.exports = {
	commonUrl: utils.commonUrl,
	judgeObj: utils.judgeObj,
	PageEntity:utils.PageEntity,
	filterSearchParam:utils.filterSearchParam,
	toast: utils.toast,
	base64ToBlob:utils.base64ToBlob,
	getTimer:utils.getTimer,
	getDay:utils.getDay,
	modal: utils.modal,
	updateAppVersion:utils.updateAppVersion,
	isAndroid: utils.isAndroid,
	isIphoneX: utils.isIphoneX,
	isIosOrAndroid:utils.isIosOrAndroid,
	constNum: utils.constNum,
	request: utils.request,
	requestDownLoad: utils.requestDownLoad,
	requestGet: utils.requestGet,
	requestScan: utils.requestScan,
	requestArry: utils.requestArry,
	uploadFile: utils.uploadFile,
	uploadFileMulti: utils.uploadFileMulti,
	uploadFileQrcod: utils.uploadFileQrcod,
	tuiJsonp: utils.tuiJsonp,
	setUserInfo: utils.setUserInfo,
	getToken: utils.getToken,
	trim: utils.trim,
	replaceAll: utils.replaceAll,
	formatNumber: utils.formatNumber,
	rmoney: utils.rmoney,
	formatDate: utils.formatDate,
	getDistance: utils.getDistance,
	isMobile: utils.isMobile,
	rgbToHex: utils.rgbToHex,
	hexToRgb: utils.hexToRgb,
	transDate: utils.transDate,
	isNumber: utils.isNumber,
	isEmpty: utils.isEmpty,
	expireTime: utils.expireTime,
	payOrder: utils.payOrder,
	login: utils.login,
	copyObjWhenKeyEqual:utils.copyObjWhenKeyEqual,
	formatrichtext:utils.formatrichtext,
	isObjEmpty:utils.isObjEmpty,
	flatten:utils.flatten,
	binarySearch:utils.binarySearch,
	randomNumber:utils.randomNumber
}
